package com.wnnight.wys.filter;


import com.wnnight.wys.entity.GlobalInfo;
import com.wnnight.wys.exception.ValidateException;
import com.wnnight.wys.util.repairs.RepairsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

public class CaptchaFilter extends OncePerRequestFilter {
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //判断访问的路径是否是登录
        if ("/api/v1/wy/login".equals(request.getRequestURI()) && "post".equalsIgnoreCase(request.getMethod())) {
            //校验
            Map<String, String> map = RepairsUtil.objectMapper.readValue(request.getInputStream(), Map.class);
            String code = map.get("code");
            GlobalInfo.account = map.get("account");
            GlobalInfo.password = map.get("password");
            GlobalInfo.type = map.get("type");
            if ("1".equals(GlobalInfo.type)) {
                if (!code.equalsIgnoreCase(GlobalInfo.code)) {
                    authenticationFailureHandler.onAuthenticationFailure(request, response, new ValidateException("验证码错误"));
                    return;
                }
            }
        }
        filterChain.doFilter(request, response);
    }
}
